package org.shzhyun.pay.Service.impl;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.shzhyun.pay.Service.WechatService;
import org.shzhyun.pay.config.Constant;
import org.apache.logging.log4j.util.Strings;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.*;

@Component
@Slf4j
public class WechatServiceImpl implements WechatService {

    @Override
    public String code2OpenId(String code, String appid) {
        String appSecret = "";
        if(Strings.isEmpty(appid)){
            appid = Constant.appId;
            appSecret = Constant.appSecret;
        }else if(Objects.equals(appid,"wx0f553a569d771f41")){
            appSecret = "1e7869efcb237137fe6f58530ce3878a";
        }else if(Objects.equals(appid,"wxe1668e897e04bb4f")){
            appSecret = "aba416eb9d2f312f8a4e0c0d176c54cb";
        }
        String url = Constant.requestUrl + "?appid=" + appid + "&secret=" + appSecret + "&js_code=" + code + "&grant_type="
                + Constant.grantType;
        RestTemplate restTemplate = new RestTemplate();
        // 发送请求
        String data = restTemplate.getForObject(url,String.class);
        log.info("请求地址：{}", url);
        log.info("请求结果：{}", data);
        JSONObject jsonObject = JSONObject.parseObject(data);
        // 形如{"session_key":"6w7Br3JsRQzBiGZwvlZAiA==","openid":"oQO565cXXXXXEvc4Q_YChUE8PqB60Y"}的字符串
        return jsonObject.getString("openid");
    }

    @Override
    public JSONObject userinfo(String code, String appid) {
        //第一步：授权token
        String appSecret = "2369a08da71cc0dfaece45108eb2dabd";
        String url = Constant.requestUrlFw + "?appid=" + appid + "&secret=" + appSecret + "&code=" + code + "&grant_type="
                + Constant.grantType;
        RestTemplate restTemplate = new RestTemplate();
        String data = restTemplate.getForObject(url,String.class);
        log.debug("请求地址：{}", url);
        log.debug("请求结果：{}", data);
        JSONObject jsonObject = JSONObject.parseObject(data);
        //第二步：获取userInfo
        url = Constant.requestUrlFwUserInfo + "?access_token="
                +jsonObject.getString("access_token")+"&openid="
                + jsonObject.getString("openid")
                + "&lang=zh_CN";
        StringHttpMessageConverter stringHttpMessageConverter = (StringHttpMessageConverter) restTemplate.getMessageConverters().get(1);
        stringHttpMessageConverter.setDefaultCharset(StandardCharsets.UTF_8);
        data = restTemplate.getForObject(url,String.class);
        log.debug("请求地址：{}", url);
        log.info("请求结果：{}", data);
        jsonObject = JSONObject.parseObject(data);
        return jsonObject;
    }

}
